#include "STLReader.h"

bool STLReader::readMeshesFromSTLFile(const QString& stl_file_path, STL_READ_TYPE stl_read_type)
{
    switch (stl_read_type)
    {
    case STL_READ_TYPE::BINARY:
        m_stlModelMeshs = readBinaryStlFile(stl_file_path);
        return true;
    case STL_READ_TYPE::ASCII:
        m_stlModelMeshs = readAsciiStlFile(stl_file_path);
        return true;
    default:
        qDebug()<<"Undefined stl type.";
        return false;
    }
}

QVector<Mesh> STLReader::getModelMeshes() const
{
    return m_stlModelMeshs;
}

QVector<Mesh> STLReader::readAsciiStlFile(const QString &filePath)
{
    QVector<Mesh> Meshs;
    QFile file(filePath);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开文件:" << file.errorString();
        return Meshs;
    }

    QTextStream in(&file);
    QString line;
    Mesh mesh;

    while (!in.atEnd()) {
        line = in.readLine().trimmed();
        QStringList tokens = line.split(" ", Qt::SkipEmptyParts);

        if (tokens.size() < 1) continue;

        if (tokens[0] == "facet" && tokens[1] == "normal") {
            mesh.normal = QVector3D(tokens[2].toFloat(), tokens[3].toFloat(), tokens[4].toFloat());
        } else if (tokens[0] == "vertex") {
            if (tokens.size() >= 4) {
                QVector3D vertex(tokens[1].toFloat(), tokens[2].toFloat(), tokens[3].toFloat());
                if (mesh.v1.isNull()) {
                    mesh.v1 = vertex;
                } else if (mesh.v2.isNull()) {
                    mesh.v2 = vertex;
                } else if (mesh.v3.isNull()) {
                    mesh.v3 = vertex;
                    Meshs.append(mesh);
                    mesh = Mesh(); // Reset for next Mesh
                }
            }
        }
    }

    file.close();
    return Meshs;
}

QVector<Mesh> STLReader::readBinaryStlFile(const QString &filePath)
{
    QVector<Mesh> meshes;
    QFile file(filePath);

    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "无法打开文件:" << file.errorString();
        return meshes;
    }

    // 读取文件头
    Head head;
    file.read(head.partName, 80); // 读取80字节的零件名称
    file.read(reinterpret_cast<char*>(&head.faceNum), 4); // 读取4字节的面数

    // 读取每个面的数据
    for (quint32 i = 0; i < head.faceNum; ++i)
    {
        Mesh mesh;
        file.read(reinterpret_cast<char*>(&mesh.normal), 12); // 读取法线
        file.read(reinterpret_cast<char*>(&mesh.v1), 12);      // 读取顶点1
        file.read(reinterpret_cast<char*>(&mesh.v2), 12);      // 读取顶点2
        file.read(reinterpret_cast<char*>(&mesh.v3), 12);      // 读取顶点3
        file.read(reinterpret_cast<char*>(&mesh.info), 2);     // 读取属性字节计数

        meshes.append(mesh);
    }

    file.close();
    return meshes;
}
